import sys
import os
import gradio as gr

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from model import OpenAIModel
from model import GLMModel
from utils import ArgumentParser, ConfigLoader,LOG
from translator import PDFTranslator


def translation(input_file, target_language,file_format):
    LOG.debug(f"[翻译任务]\n源文件: {input_file.name} \n目标语言: {target_language} \n 输出格式:{file_format}")

    output_file_path = Translator.translate_pdf(
        input_file,file_format, target_language=target_language)

    return output_file_path

def launch_gradio():

    iface = gr.Interface(
        fn=translation,
        title="OpenAI-Translator v2.0(PDF 电子书翻译工具)",
        inputs=[
            gr.File(label="上传PDF文件"),
            gr.Textbox(label="目标语言（默认：中文）", placeholder="中文", value="中文"),
            gr.Dropdown(["PDF","Markdown"], value="PDF", label="输出文件格式")
        ],
        outputs=[
            gr.File(label="下载翻译文件")
        ],
        allow_flagging="never"
    )

    iface.launch()

def initialize_translator():
    # 解析命令行
    argument_parser = ArgumentParser()
    
    args = argument_parser.parse_arguments()
    config_loader = ConfigLoader(args.config)

    config = config_loader.load_config()


    model_type = args.model_type 
    model_name = args.openai_model if args.openai_model else config['OpenAIModel']['model']
    api_key = args.openai_api_key if args.openai_api_key else config['OpenAIModel']['api_key']
    model_url = args.glm_model_url if args.glm_model_url else config['GLMModel']['model_url']
    timeout = args.timeout if args.timeout else config['GLMModel']['timeout']
    
    if model_type=="OpenAIModel":
        model = OpenAIModel(model=model_type, api_key=api_key)
    elif model_type=="GLMModel":
        model = GLMModel(model_url,timeout) 
    else:
        raise ValueError(f"Unsupported model name: {model_type}")


    # 实例化 PDFTranslator 类，并调用 translate_pdf() 方法
    global Translator
    Translator = PDFTranslator(model)


if __name__ == "__main__":
    # 初始化 translator
    initialize_translator()
    # 启动 Gradio 服务
    launch_gradio()
